
package managedbean;

import java.io.Serializable;
import java.util.Properties;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;

import jpa.CustomerJPA;
import jpa.ShoppingCart;
import ejb.CustomerFacadeRemote;

/**
 * Managed Bean LoginMBean
 */
@ManagedBean(name = "customerLogin")
@SessionScoped
public class LoginMBean implements Serializable{
	
	
	private static final long serialVersionUID = 1L;
	
	@EJB
	private CustomerFacadeRemote customerRemote;
	
	protected CustomerJPA dataCustomer = new CustomerJPA();
	
	public LoginMBean(){
	}

	public CustomerJPA getDataCustomer()
	{
		return dataCustomer;
	}	
	public void setDataCustomer(CustomerJPA customer)
	{
		this.dataCustomer=customer;
	}
	
	/**
	 * Method to prepare for logging in
	 */
	public String loginMBean() throws Exception{
		login();
		FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("loginController", dataCustomer);
		if(dataCustomer.getName()==null){
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid e-mail or password.", dataCustomer.getEmail());
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}
		return "homeView.xhtml";
	}
	
	/**
	 * Method to log in
	 */
	public void login() throws Exception{
		Properties props = System.getProperties();
		Context ctx = new InitialContext(props);
		customerRemote = (CustomerFacadeRemote) ctx.lookup("java:app/PracticalCaseStudyJEE.jar/CustomerFacadeBean!ejb.CustomerFacadeRemote");
		dataCustomer = customerRemote.login(dataCustomer.getEmail(), dataCustomer.getPassword());
		FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("shoppingCart", new ShoppingCart());
	}
	
	/**
	 * Method to prepare for logging out
	 */
	public String logoutMBean() throws Exception{
		logout();
		return "homeView.xhtml";
	}
	
	/**
	 * Method to log in
	 */
	public void logout() throws Exception{
		Properties props = System.getProperties();
		Context ctx = new InitialContext(props);
		customerRemote = (CustomerFacadeRemote) ctx.lookup("java:app/PracticalCaseStudyJEE.jar/CustomerFacadeBean!ejb.CustomerFacadeRemote");
		FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("loginController");
		dataCustomer = customerRemote.logout();
		//FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
	}

}
